﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using kwzx.Common;
using System.Threading;
using System.Diagnostics;
using System.Net;

namespace kwzx
{
    public partial class dbrw_dwfk : Form
    {
        //东屋  
        public const short ORDER_OK = 0x30;

        DataSet1TableAdapters.K_DeviceIssueTableAdapter k_deviceIssue = new DataSet1TableAdapters.K_DeviceIssueTableAdapter();
        DataSet1TableAdapters.CD_CardTypeTableAdapter cd_card = new DataSet1TableAdapters.CD_CardTypeTableAdapter();
        DataSet1TableAdapters.K_kwzxrwTableAdapter kwzxrw = new DataSet1TableAdapters.K_kwzxrwTableAdapter();
        DataSet1TableAdapters.K_CardTableAdapter k_card = new DataSet1TableAdapters.K_CardTableAdapter();
           
        int userid = 0;
        int kwzxrwid = 0;
        string fkbk = "授权";

        public dbrw_dwfk()
        {
            InitializeComponent();
        }
        public dbrw_dwfk(int kwzxrwid1, int userid1)
        {
            userid = userid1;
            kwzxrwid = kwzxrwid1;
            InitializeComponent();
        }
        /// <summary>
        /// dbrw_dwfk_Load
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dbrw_dwfk_Load(object sender, EventArgs e)
        {
            // TODO: 这行代码将数据加载到表“dataSet1.T_BM”中。您可以根据需要移动或删除它。
            this.t_BMTableAdapter.Fill(this.dataSet1.T_BM);
            // TODO: 这行代码将数据加载到表“dataSet1.X_CS_DETAIL”中。您可以根据需要移动或删除它。
            this.x_CS_DETAILTableAdapter.Fill(this.dataSet1.X_CS_DETAIL);

            ksdateDateTimePicker.Text = DateTime.Now.ToShortDateString();
            jsdateDateTimePicker.Text = DateTime.Now.AddYears(30).ToShortDateString(); 

            //表T_USER，加载参数userid的用户信息
            this.t_USERTableAdapter.FillBy_ID(this.dataSet1.T_USER, userid);

            this.m_user_door_logTableAdapter.FillBy_user_id(this.dataSet1.M_user_door_log, userid);

            //查出门号
            this.v_DW_doorTableAdapter.FillBy_user_id(this.dataSet1.V_DW_door, userid);
            smTextBox.Text = "";
            for (int i = 0; i < this.dataSet1.V_DW_door.Rows.Count; i++)
            {
                if (smTextBox.Text != "")
                {
                    smTextBox.Text += ":" + dataSet1.V_DW_door.Rows[i]["bh"].ToString();
                }
                else
                {
                    smTextBox.Text = dataSet1.V_DW_door.Rows[i]["bh"].ToString();
                }
            }
            //获取FTP上的照片
            if (t_USERBindingSource.Current != null)
            {
                string users_id9 = ((DataRowView)t_USERBindingSource.Current)["user_id"].ToString();
                string Imgpath = ((DataRowView)t_USERBindingSource.Current)["zp"].ToString(); ;
                if (!string.IsNullOrWhiteSpace(Imgpath))
                {
                    int x = Imgpath.IndexOf("ftp/") + 4;
                    string userImg = Imgpath.Substring(x, Imgpath.Length - x);
                    int userImginfo = userImg.IndexOf("/") + 1;

                    string zpname = users_id9 + ".dat";
                    string kkzp = FileTran.DownloadFile(SPicUtils.path, zpname, userImg);
                    this.pictureBox1.Image = SPicUtils.PicConvert(kkzp);
                    //FileTran.DownloadFile(SPicUtils.path, "", userImg);
                    //string imgname = userImg.Substring(userImginfo, (userImg.Length - userImginfo));
                    //this.pictureBox1.Image = SPicUtils.PicConvert(SPicUtils.path + imgname);
                }
                else
                {
                    pictureBox1.Image = global::kwzx.Properties.Resources.无图片;
                }
            }
        }
        /// <summary>
        /// 起动服务
        /// </summary>
        /// <returns></returns>
        private bool dwserver()
        {
            try
            {
                string exename = Properties.Settings.Default.exe_dwname;
                if (exename != "")
                {
                    string name1 = exename.Substring(exename.LastIndexOf("\\") + 1, exename.Length - exename.LastIndexOf("\\") - 1);
                    Process[] p = Process.GetProcessesByName(name1);
                    if (p.Length == 0)
                    {
                        p = Process.GetProcessesByName(name1.Replace(".exe", ""));
                    }

                    if (p.Length == 0)
                    {
                        Process.Start(exename);
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show("东屋写卡服务起动失败");
                return false;
            }
        }
        /// <summary>
        /// 写卡操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            DataTable kcarddt = k_card.GetDataBy_user_id(userid);
            if (kcarddt.Rows.Count > 0)
            {
                string kh = kcarddt.Rows[0]["kh"].ToString();
                if (kh == "")
                {
                    MessageBox.Show("未分配卡号，请先分配卡！");
                    return;
                }
                if (smTextBox.Text.Trim() == "")
                {
                    MessageBox.Show("没有分配房间,请先分配后写卡");
                    return;
                }
                DataSet1TableAdapters.M_user_door_logTableAdapter M_user_door_log = new DataSet1TableAdapters.M_user_door_logTableAdapter();

                try
                {
                    //更新卡号到卡表
                    DataSet1TableAdapters.K_CarddataTableAdapter kcad = new DataSet1TableAdapters.K_CarddataTableAdapter();
                    int user_id = userid;
                    DateTime ksdate = DateTime.Parse(ksdateDateTimePicker.Value.ToShortDateString());
                    DateTime jsdate = DateTime.Parse(jsdateDateTimePicker.Value.ToShortDateString());

                    string SM = smTextBox.Text;
                    DateTime gxdate = DateTime.Now;
                    string zt = fkbk;
                    string lrz = Utils.CurrentUser.xm;
                    DateTime zzdate = DateTime.Now;
                    string czr = Utils.CurrentUser.xm;

                    M_user_door_log.InsertQuery(user_id, ksdate, jsdate, gxdate, kh, zt, SM, zzdate, czr);
                    //东屋
                    //起动东屋写卡服务
                    if (!dwserver())
                    {
                        return;
                    }

                    string dwip = Properties.Settings.Default.dwfkqip;
                    if (dwip == "127.0.0.1")
                    {
                        IPHostEntry IpEntry = Dns.GetHostEntry(Dns.GetHostName());

                        for (int i = 0; i != IpEntry.AddressList.Length; i++)
                        {
                            if (!IpEntry.AddressList[i].IsIPv6LinkLocal)
                            {
                                //MessageBox.Show(IpEntry.AddressList[i].ToString());
                                string myip = IpEntry.AddressList[0].ToString();
                                dwip = myip;
                            }
                        }
                    }
                    int mycnn = dwkey.TCPCONNECT(dwip);
                    if (mycnn == 48)
                    {
                        int CardID = 0;
                        //KeyType类型          Gname宾客姓名,GID:,证件号      RoomName:房间名称         卡片有效期   KStart,  KEnd   CardID:返回的卡号
                        int dwid = dwkey.TCP_KEY(00, xMTextBox.Text, sfzhTextBox.Text, SM, ksdate.ToString(), jsdate.ToString(), ref CardID);
                        dwkey.TCPDISCONNECT();
                        textBox1.Text = xMTextBox.Text + "写卡成功";
                        // MessageBox.Show("写卡成功！");
                    }
                    else
                    {
                        dwkey.TCPDISCONNECT();
                        MessageBox.Show("写卡失败！");
                    }

                    // TODO: 这行代码将数据加载到表“dataSet1.M_user_door_log”中。您可以根据需要移动或删除它。
                    this.m_user_door_logTableAdapter.FillBy_user_id(this.dataSet1.M_user_door_log, Convert.ToInt32(user_id));

                    Thread.Sleep(500);
                    //调用读卡操作，显示授权情况
                    button3_Click(sender, e);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            else
            {
                MessageBox.Show("该人员未分配卡号，不能授权！");
            }
        }
        /// <summary>
        /// 关闭窗口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.OK;
            this.Close();
        }
        /// <summary>
        /// 读卡操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            //起动写卡服务
            if (!dwserver())
            {
                return;
            }
            
            textBox1.Text = "";
            string dwip = Properties.Settings.Default.dwfkqip;
            if (dwip == "127.0.0.1")
            {
                IPHostEntry IpEntry = Dns.GetHostEntry(Dns.GetHostName());

                for (int i = 0; i != IpEntry.AddressList.Length; i++)
                {
                    if (!IpEntry.AddressList[i].IsIPv6LinkLocal)
                    {
                        //MessageBox.Show(IpEntry.AddressList[i].ToString());
                        string myip = IpEntry.AddressList[0].ToString();
                        dwip = myip;
                    }
                }
            }
            int mycnn = dwkey.TCPCONNECT(dwip);
            if (mycnn == 48)
            {
                dwkey.PChar pc = new dwkey.PChar();
                byte KeyType = 00;
                dwkey.PChar GName = new dwkey.PChar();
                dwkey.PChar GID = new dwkey.PChar();
                dwkey.PChar RoomName = new dwkey.PChar();
                dwkey.PChar KStart = new dwkey.PChar();
                dwkey.PChar KEnd = new dwkey.PChar();
                int CardID = 0;
                byte myresult;

                try
                {
                    myresult = dwkey.TCP_CHECKCARD(ref KeyType, ref GName, ref GID, ref RoomName, ref KStart, ref KEnd, ref CardID);
                    dwkey.TCPDISCONNECT();
                    string GName1 = new string(GName.MyGetData).Replace("\0", "");
                    string GID1 = new string(GID.MyGetData).Replace("\0", "");
                    string KStart1 = new string(KStart.MyGetData).Replace("\0", "");
                    string KEnd1 = new string(KEnd.MyGetData).Replace("\0", "");
                    string RoomName1 = new string(RoomName.MyGetData).Replace("\0", "");

                    this.textBox1.Text = CardID.ToString() + "\r\n" + GName1 + "\r\n" + GID1 + "\r\n" + KStart1 + "\r\n" + KEnd1 + "\r\n" + RoomName1 + "\r\n";
                    if (RoomName1 != smTextBox.Text)
                    {
                        MessageBox.Show("房间号不一致,请检查");
                    }
                    if (myresult == ORDER_OK)
                    {

                    }
                    else
                    {
                        MessageBox.Show(myresult.ToString() + "Error");
                    }
                }
                catch
                {
                    dwkey.TCPDISCONNECT();
                    MessageBox.Show("00");
                }
            }
            else
            {
                dwkey.TCPDISCONNECT();
            }
        }
        /// <summary>
        /// 消除卡操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button4_Click(object sender, EventArgs e)
        {
            //起动东屋写卡服务
            if (!dwserver())
            {
                return;
            }

            string dwip = Properties.Settings.Default.dwfkqip;
            if (dwip == "127.0.0.1")
            {
                IPHostEntry IpEntry = Dns.GetHostEntry(Dns.GetHostName());

                for (int i = 0; i != IpEntry.AddressList.Length; i++)
                {
                    if (!IpEntry.AddressList[i].IsIPv6LinkLocal)
                    {
                        //MessageBox.Show(IpEntry.AddressList[i].ToString());
                        string myip = IpEntry.AddressList[0].ToString();
                        dwip = myip;
                    }
                }
            }
            int mycnn = dwkey.TCPCONNECT(dwip);
            if (mycnn == 48)
            {
                dwkey.TCP_CHECKOUT("1101", true);
                dwkey.TCPDISCONNECT();
            }
            else
            {
                dwkey.TCPDISCONNECT();
            }
        }
        /// <summary>
        /// 计算日期
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ksdateDateTimePicker_ValueChanged(object sender, EventArgs e)
        {
            int kkl = (((DateTime.Parse(jsdateDateTimePicker.Text) - DateTime.Parse(ksdateDateTimePicker.Text)).Days) / 365);
            textBox4.Text = kkl.ToString();
        }
        /// <summary>
        /// 计算日期
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void jsdateDateTimePicker_ValueChanged(object sender, EventArgs e)
        {
            int kkl = (((DateTime.Parse(jsdateDateTimePicker.Text) - DateTime.Parse(ksdateDateTimePicker.Text)).Days) / 365);
            textBox4.Text = kkl.ToString();
        }
        /// <summary>
        /// 流程手动操作完成.修改记录的状态,刷新界面显示
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button5_Click(object sender, EventArgs e)
        {
            DataTable kwzxrwdt = kwzxrw.GetDataBy_kwzxrwid(kwzxrwid);
            if (kwzxrwdt.Rows.Count > 0)
            {
                kwzxrw.UpdateQuery_czzt("手动完成(已完成)", kwzxrwid);
            }
            MessageBox.Show("成功！");
            this.Close();
            this.DialogResult = DialogResult.OK;
        }
    }
}
